package com.wn.controller;

import com.wn.entity.Booktype;
import com.wn.model.Result;
import com.wn.servicer.BooktypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.util.Date;
import java.util.List;


@RestController
@RequestMapping("/booktype")
public class BookTypeController {


    @Autowired
    RedisTemplate<String,Object> stringObjectRedisTemplate;

    @Autowired
    BooktypeService booktypeService;


    @RequestMapping("/queryall")
    public Result<List<Booktype>> queryall(){
        ValueOperations<String,Object> valueOperations = stringObjectRedisTemplate.opsForValue();
        Object booktypes = valueOperations.get("booktypeList");
        List<Booktype> booktypeList = null;
        if (booktypes == null){
            booktypeList = booktypeService.list();
            valueOperations.set("booktypeList",booktypeList);
        }else {
            booktypeList = (List<Booktype>) booktypes;
        }
        return Result.successResult(booktypeList);
    }

    @RequestMapping("/add")
    public Result<String> add(String name){
        stringObjectRedisTemplate.delete("booktypeList");
        Booktype booktype = new Booktype();
        booktype.setName(name);
        booktype.setCreatetime(new Date());
        booktype.setUpdatetime(new Date());
        booktypeService.save(booktype);
        return Result.successResult("添加成功");
    }

    @DeleteMapping("/delete/{id}")
    public Result<String> delete(@PathVariable Integer id){
        stringObjectRedisTemplate.delete("booktypeList");
        booktypeService.removeById(id);
        return Result.successResult("删除成功");
    }

    @RequestMapping("/queryById/{id}")
    public Result<Booktype> queryById(@PathVariable Integer id){
        Booktype booktype = booktypeService.getById(id);
        return Result.successResult(booktype);
    }

    @RequestMapping("/update")
    public Result<String> update(@RequestBody Booktype booktype){
        stringObjectRedisTemplate.delete("booktypeList");
        booktype.setUpdatetime(new Date());
        booktypeService.updateById(booktype);
        return Result.successResult("更新成功");
    }
}
